package security.handler;/**
 * @Auther: liyipeng
 * @Date: 2020/1/16 18:54
 * @Description:
 */

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import util.Object2JsonString2ObjectUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>类名: JwtLogFailureHandler</p>
 * <p>描述:TODO</p>
 * <p>创建人: liyp</p>
 * <p>创建时间: 2020/1/16 18:54</p>
 * <p>@version 2.0  </p>
 * <p>修改内容: ......</p>
 * <p>修改说明: ......</p>
 * <p>修改时间: ......</p>
 * <p>修改人: ......</p>
 * <p>每次修改，请增加上述修改信息说明</>
 */
public class JwtLogFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        Map<String, Object> paramMap = new HashMap<>();
        if(e instanceof BadCredentialsException){
            paramMap.put("code", "400103");
            paramMap.put("message", "您尚未登录，请重新登录");
        }else if(e instanceof InternalAuthenticationServiceException){
            paramMap.put("code", "400102");
            paramMap.put("message", "用户名不存在!");
        }else if(e instanceof InsufficientAuthenticationException){
            paramMap.put("code", "400104");
            paramMap.put("message", "认证信息为空，您不能进行该操作");
        }
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter out = httpServletResponse.getWriter();
        out.write(Object2JsonString2ObjectUtil.Object2JsonString(paramMap));
        out.flush();
        out.close();
    }
}
